/** crm自定义列表 公共逻辑 */
import {
  filedGetTableFieldAPI,
  filedGetPoolTableFieldAPI,
  crmFieldColumnWidthAPI,
  crmPoolFieldColumnWidthAPI
} from '@/api/crm/common'
import {
  crmCustomerIndexAPI,
  crmCustomerPoolListAPI,
  crmCustomerExcelAllExportAPI,
  crmCustomerPoolExcelAllExport,
  crmCustomerStarAPI
} from '@/api/crm/customer'
import {
  crmCustomerVipIndexAPI,
  crmCustomerVipExcelAllExportAPI,
  crmCustomerVipStarAPI
} from '@/api/crm/vipStudents'
import {
  crmLeadsIndexAPI,
  crmLeadsExcelAllExportAPI,
  crmLeadsStarAPI
} from '@/api/crm/leads'
import {
  crmRoiIndexAPI,
  crmPutinAllianceBusinessAPI,
  crmRoiExcelAllExportAPI
} from '@/api/crm/roiMoney'
import {
  crmAllianceBusinessIndexAPI,
  allianceBusinessBalanceIndexAPI,
  crmHeadquartersBusinessIndexAPI,
  crmHeadquartersBusinessBalanceIndexAPI
} from '@/api/crm/allianceBusiness'
import {
  crmLargeScreenSettingIndexAPI
} from '@/api/crm/crmLargeScreenSetting'
import {
  crmputinStatisticsIndexAPI,
  crmputinStatisticsExcelAllExportAPI,
  crmPutinStatisticsAllianceBusinessIndexAPI
} from '@/api/crm/putinStatistics'
import {
  crmContactsIndexAPI,
  crmContactsExcelAllExportAPI,
  crmContactsStarAPI
} from '@/api/crm/contacts'
import {
  crmBusinessIndexAPI,
  crmBusinessExcelAllExportAPI,
  crmBusinessStarAPI
} from '@/api/crm/business'
import {
  crmContractIndexAPI,
  crmContractExcelAllExportAPI
} from '@/api/crm/contract'
import {
  crmProductIndexAPI,
  crmProductExcelAllExportAPI
} from '@/api/crm/product'
import {
  crmReceivablesIndexAPI,
  crmReceivablesExcelAllExportAPI
} from '@/api/crm/receivables'
import {
  crmRefundIndexAPI,
  crmRefundExcelAllExportAPI
} from '@/api/crm/refund'
import {
  crmOverdueIndexAPI,
  crmOverdueExcelAllExportAPI
} from '@/api/crm/overdue'
import {
  crmReturnVisitIndexAPI
} from '@/api/crm/visit'
import {
  crmSourceListAPI
} from '@/api/crm/source'

import WkEmpty from '@/components/WkEmpty'
import CRMListHead from '../components/CRMListHead'
import CRMTableHead from '../components/CRMTableHead'
import CRMNewHead from '../components/CRMNewHead' // 新 标头操作head
import FieldSet from '../components/FieldSet'
import ApprovalFlowUpdateDialog from '@/components/ApprovalFlow/ApprovalFlowUpdateDialog'
import CRMNewTableManage from '../components/CRMNewTableManage'

import {
  mapGetters
} from 'vuex'
import crmTypeModel from '@/views/crm/model/crmTypeModel'
import Lockr from 'lockr'
import {
  Loading
} from 'element-ui'
import CheckStatusMixin from '@/mixins/CheckStatusMixin'
import {
  separator
} from '@/filters/vueNumeralFilter/filters'
import {
  downloadExcelWithResData
} from '@/utils'

export default {
  components: {
    CRMListHead,
    CRMTableHead,
    CRMNewHead,
    FieldSet,
    WkEmpty,
    ApprovalFlowUpdateDialog,
    CRMNewTableManage
  },
  data() {
    return {
      loading: false, // 加载动画
      list: [],
      fieldList: [],
      sortData: {}, // 字段排序
      currentPage: 1,
      pageSize: Lockr.get('crmPageSizes') || 15,
      pageSizes: [15, 30, 60, 100],
      total: 0,
      search: '', // 搜索内容
      /** 控制详情展示 */
      rowID: '', // 行信息
      rowType: '', // 详情类型
      showDview: false,
      /** 高级筛选 */
      filterObj: [], // 筛选确定数据
      sceneId: '', // 场景筛选ID
      sceneName: '', // 场景名字
      /** 勾选行 */
      selectionList: [], // 勾选数据 用于全局导出
      // 金额字段
      moneyFields: [],
      // 已经发请求 用于缓存区分
      isRequested: false,

      defaultGenerate: 0,
      removeHeight: 0
    }
  },

  mixins: [CheckStatusMixin],

  computed: {
    ...mapGetters(['crm', 'agreement']),
    saveAuth() {
      if (this.isSeas) {
        return false
      }
      return this.crm[this.crmType].save
    },
    // table高度
    tableHeight() {
      var offsetHei = document.documentElement.clientHeight
      let height = 0;
      if (this.crm && this.crm.vipPool && this.crm.vipPool.index && this.crmType == 'vipStudents') {
        height = offsetHei - this.removeHeight - 261 - 48
      } else if (this.crm && this.crm.orderPool && this.crm.orderPool.index && this.crmType == 'contract') {
        height = offsetHei - this.removeHeight - 261 - 48 - 40 - 16
      } else if (this.crmType == 'contract') {
        height = offsetHei - this.removeHeight - 261 - 40 - 16
      }
      else {
        height = offsetHei - this.removeHeight - 261
      }
      return height;
    }
  },
  watch: {},
  mounted() {
    // document.getElementById('crm-table').addEventListener('click', e => {
    //   e.stopPropagation()
    // })
    if (this.isSeas && this.crm.pool.index) {
      this.getFieldList()
    } else if (this.crm[this.crmType].index) {
      this.loading = true
    }
    this.$bus.on('updateList', this.searchTable)
  },
  methods: {
    // 列表状态字段颜色区分
    statusClass(row, column, rowIndex, columnIndex) {
      if (column.property === "vipDealStatus") {//成交状态 
        return row.vipDealStatus == "已成交" ? "color-green" : "color-red"
      } else if (column.property === "studentStatus") {//学员状态
        return row.studentStatus === 1 ? "color-green" : row.studentStatus === 0 ? "color-red" : ""
      } else if (column.property === "repaymentStatus") {//还款状态
        let rStus = row.repaymentStatus
        if (rStus == "还款中") return "color-blue"
        else if (rStus == "已还清") return "color-green"
        else if (rStus == "已逾期" || rStus == "已代偿") return "color-yellow"
        else if (rStus == "已退学" || rStus == "退学中" || rStus == "已作废" || rStus == "已冻结") return "color-red"
        else return ""
      }
      else {
        return ""
      }
    },
    // 自定义搜索
    searchTable() {
      this.currentPage = 1
      this.getList()
    },

    setFixedHeight(h) {
      document.querySelector(".el-table__fixed").style.height = h - 8 + 'px';
      document.querySelector('.el-table__fixed-right').style.height = h - 8 + 'px';
    },

    /** 获取列表数据 */
    getList() {
      this.loading = true
      var crmIndexRequest = this.getIndexRequest()
      var params = {
        page: this.currentPage,
        limit: this.pageSize,
        search: this.search,
        type: this.isSeas ? crmTypeModel.pool : crmTypeModel[this.crmType] // 9是公海
      }
      if (this.crmType == 'contract') {//合同tab切换
        if (this.activeName == 'second') {
          params.contractCategory = '账单合同'
        } else if (this.activeName == 'third') {
          params.contractCategory = '首付款合同'
        } else if (this.activeName == 'fourth') {
          params.contractCategory = '全款/复购合同'
        } else if (this.activeName == 'fifth') {
          params.contractCategory = '线下合同'
        }
      }
      if (this.crmType == 'roiMoney' || this.crmType == 'putinStatistics' || this.crmType == 'crmPutinAllianceBusiness' || this.crmType == 'putinStatisticsAllianceBusiness') {
        let cateArr = [];
        for (let i = 0; i < this.tfvalue_ses.length; i++) {
          const cateVal = {
            '电商美工': 1,
            '手绘插画': 2,
            '影视后期': 3
          }[this.tfvalue_ses[i]];
          cateArr.push(cateVal)
        }
        params.deptIds = this.deptIds_s;
        params.categoryStr = cateArr.toString();
        params.coursePeriods = this.kcinput_s;
        if (this.datevalue_s) {
          params.startDate = this.datevalue_s[0];
          params.endDate = this.datevalue_s[1];
        }
        params.putinPlatform = this.tfvalue_s.toString();
      }
      if (this.crmType == 'allianceBusiness' || this.crmType == 'allianceBusinessBalance') {
        params.putinPlatform = this.tfvalue_s.toString();
        params.deptIds = this.deptIds_s;
      }
      if (this.crmType == 'headquartersBusiness' || this.crmType == 'headquartersBusinessBalance') {
        params.deptIds = this.deptIds_s;
      }
      if (this.crmType == 'crmLargeScreenSetting') {
        params.settingName = this.settingName_s;
      }
      if (this.crmType == 'customerSource') {
        if (this.categoryName_s) {
          params.categoryCode = this.categoryName_s;
        }
        if (this.source_s) {
          params.source = this.source_s;
        }
      }
      if (this.sortData.order) {
        params.sortField = this.sortData.prop
        params.order = this.sortData.order == 'ascending' ? 2 : 1
      }
      if (this.sceneId) {
        params.sceneId = this.sceneId
      }

      // 公海切换
      if (this.poolId) {
        params.poolId = this.poolId
      }
      if (this.filterObj && this.filterObj.length > 0) {

        params.searchList = this.filterObj

      }
      if (this.crmType == 'receivables') {
        params.defaultGenerate = this.defaultGenerate
      }
      if (this.refundCategory) {
        params.refundCategory = this.refundCategory;
      }
      crmIndexRequest(params)
        .then(res => {
          // 需为true 才会触发学员列表和公海列表展示之后的刷新
          this.isRequested = true

          if (this.crmType === 'customer') {
            this.list = res.data.list.map(element => {
              element.show = false // 控制列表商机展示
              return element
            })
          } else if (this.crmType === 'roiMoney' || this.crmType === 'crmPutinAllianceBusiness') {
            this.moneyData = res.data.extraData;
            this.list = res.data.list;
          } else if (this.crmType === 'allianceBusiness') {
            console.log(res.data.list);
            this.list = res.data.list;
          } else if (this.crmType === 'putinStatistics' || this.crmType === 'putinStatisticsAllianceBusiness') {
            const obj = res.data.extraData;
            if (obj) {
              Object.keys(this.putinStatisticsData).forEach((key) => {
                this.putinStatisticsData[key] = obj[key] || this.putinStatisticsData[key];
              });
            } else {
              Object.keys(this.putinStatisticsData).forEach((key) => {
                this.putinStatisticsData[key] = '0';
              });
            }

            this.list = res.data.list;
          } else if (this.crmType === 'customerSource') {
            this.list = res.data.list;
          } else {
            if (this.crmType === 'contract' ||
              this.crmType === 'receivables' ||
              this.crmType === 'business' ||
              this.crmType === 'overdue' ||
              this.crmType === 'refund'
            ) {
              // 合同/回款列表展示金额信息
              this.moneyData = res.data.extraData ? res.data.extraData.money || {} : {}
            }
            this.list = res.data.list
          }

          if (res.data.totalRow && Math.ceil(res.data.totalRow / this.pageSize) < this.currentPage && this
            .currentPage > 1) {
            this.currentPage = this.currentPage - 1
            this.getList()
          } else {
            this.total = res.data.totalRow
            this.loading = false
          }
          this.$nextTick(() => {
            document.querySelector('.el-table__body-wrapper').scrollTop = 0;
            this.setFixedHeight(this.tableHeight)
          })

        })
        .catch(() => {
          this.loading = false
        })
    },
    /** 获取列表请求 */
    getIndexRequest() {
      if (this.crmType === 'leads') {
        return crmLeadsIndexAPI
      } else if (this.crmType === 'roiMoney') {
        return crmRoiIndexAPI
      } else if (this.crmType === 'crmPutinAllianceBusiness') {
        return crmPutinAllianceBusinessAPI
      } else if (this.crmType === 'allianceBusiness') {
        return crmAllianceBusinessIndexAPI
      } else if (this.crmType === 'allianceBusinessBalance') {
        return allianceBusinessBalanceIndexAPI
      } else if (this.crmType === 'headquartersBusiness') {
        return crmHeadquartersBusinessIndexAPI
      } else if (this.crmType === 'headquartersBusinessBalance') {
        return crmHeadquartersBusinessBalanceIndexAPI
      } else if (this.crmType === 'putinStatistics') {
        return crmputinStatisticsIndexAPI
      } else if (this.crmType === 'putinStatisticsAllianceBusiness') {
        return crmPutinStatisticsAllianceBusinessIndexAPI
      } else if (this.crmType === 'crmLargeScreenSetting') {
        return crmLargeScreenSettingIndexAPI
      } else if (this.crmType === 'customer') {
        if (this.isSeas) {
          return crmCustomerPoolListAPI
        } else {
          return crmCustomerIndexAPI
        }
      } else if (this.crmType === 'contacts') {
        return crmContactsIndexAPI
      } else if (this.crmType === 'business') {
        return crmBusinessIndexAPI
      } else if (this.crmType === 'contract') {
        return crmContractIndexAPI
      } else if (this.crmType === 'product') {
        return crmProductIndexAPI
      } else if (this.crmType === 'receivables') {
        return crmReceivablesIndexAPI
      } else if (this.crmType === 'visit') {
        return crmReturnVisitIndexAPI
      } else if (this.crmType === 'vipStudents') {
        return crmCustomerVipIndexAPI
      } else if (this.crmType === 'customerSource') {
        return crmSourceListAPI
      } else if (this.crmType === 'refund') {
        return crmRefundIndexAPI
      } else if (this.crmType === 'overdue') {
        return crmOverdueIndexAPI
      }
    },
    /** 获取字段 */
    getFieldList(force) {
      if (this.fieldList.length == 0 || force) {
        this.loading = true
        const params = {}
        if (this.isSeas) {
          params.label = 2
          if (this.poolId) {
            params.poolId = this.poolId
          }
        } else {
          params.label = this.crmType == 'vipStudents' ? 19 : crmTypeModel[this.crmType];
        }
        if ((params.label < 19 || params.label == 25 || params.label == 24 || params.label == 19)) {
          const request = this.isSeas ? filedGetPoolTableFieldAPI : filedGetTableFieldAPI
          request(params)
            .then(res => {
              const fieldList = []
              const moneyFields = []
              for (let index = 0; index < res.data.length; index++) {
                const element = res.data[index]
                var width = 0
                if (!element.width) {
                  if (element.name && element.name.length <= 6) {
                    width = element.name.length * 15 + 45
                  } else {
                    width = 140
                  }
                } else {
                  width = element.width
                }

                // 金额字段 需要格式化
                if (element.formType === 'floatnumber') {
                  moneyFields.push(element.fieldName || '')
                }

                fieldList.push({
                  prop: element.fieldName,
                  label: element.name,
                  width: width,
                  sortId: element.id
                })
              }
              this.moneyFields = moneyFields
              this.fieldList = fieldList
              // 获取好字段开始请求数据
              this.getList()
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          var data = [];
          if (params.label == 77) {
            data = [{
              fieldName: 'putinPlatform',
              name: '投放平台',
              id: 1,
              sort: true,
              width: "200px",
              prop: 'putinPlatform'
            },
            {
              fieldName: 'category',
              name: '大类',
              id: 13,
              sort: true,
              prop: 'category'
            },
            {
              fieldName: 'deptName',
              name: '合伙人名称',
              id: 1,
              width: '200px',
              prop: 'deptName'
            },
            {
              fieldName: 'putinMoney',
              name: '渠道充值金额',
              id: 2,
              sort: true,
              prop: 'putinMoney'
            },
            {
              fieldName: 'practicalPutinMoney',
              name: '渠道消耗金额',
              id: 3,
              sort: true,
              prop: 'practicalPutinMoney'
            },
            {
              fieldName: 'putinRebatesMoney',
              name: '渠道返点金额',
              id: 4,
              sort: true,
              prop: 'putinRebatesMoney'
            },
            {
              fieldName: 'putinCompensateMoney',
              name: '渠道赔付金额',
              id: 5,
              sort: true,
              prop: 'putinCompensateMoney'
            },
            {
              fieldName: 'rollinMoney',
              name: '渠道转入金额',
              id: 6,
              sort: true,
              prop: 'rollinMoney'
            },
            {
              fieldName: 'rolloutMoney',
              name: '渠道转出金额',
              id: 7,
              sort: true,
              prop: 'rolloutMoney'
            },

            {
              fieldName: 'remark',
              name: '备注',
              id: 8,
              prop: 'remark'
            },
            {
              fieldName: 'putinFormDate',
              name: '表单录入时间',
              id: 9,
              sort: true,
              prop: 'putinFormDate'
            },
            {
              fieldName: 'createTime',
              name: '创建时间',
              id: 14,
              sort: true,
              prop: 'createTime'
            },
            {
              fieldName: 'fileName',
              name: '打款截图',
              id: 11,
              sort: true,
              prop: 'fileName'
            },
            {
              fieldName: 'putinUserName',
              name: '创建人',
              id: 12,
              sort: true,
              prop: 'putinUserName'
            },
            {
              fieldName: 'checkStatus',
              name: '审核状态',
              id: 10,
              prop: 'checkStatus'
            },
            ]
          } else if (params.label == 100) {
            data = [{
              fieldName: 'putinPlatform',
              name: '投放平台',
              id: 1,
              sort: true,
              width: "200px",
              prop: 'putinPlatform'
            },
            {
              fieldName: 'category',
              name: '大类',
              id: 13,
              sort: true,
              prop: 'category'
            },
            {
              fieldName: 'deptName',
              name: '组织',
              id: 3,
              sort: true,
              prop: 'deptName'
            },
            {
              fieldName: 'putinFormDate',
              name: '表单录入时间',
              id: 9,
              sort: true,
              prop: 'putinFormDate'
            },
            {
              fieldName: 'putinMoney',
              name: '渠道充值金额',
              id: 2,
              sort: true,
              prop: 'putinMoney'
            },
            {
              fieldName: 'practicalPutinMoney',
              name: '渠道消耗金额',
              id: 3,
              sort: true,
              prop: 'practicalPutinMoney'
            },
            {
              fieldName: 'formNum',
              name: '表单数',
              id: 3,
              sort: true,
              prop: 'formNum'
            },
            {
              fieldName: 'avgPrice',
              name: '均价',
              id: 3,
              sort: true,
              prop: 'avgPrice'
            },
            {
              fieldName: 'fileName',
              name: '打款截图',
              id: 11,
              sort: true,
              prop: 'fileName'
            },
            {
              fieldName: 'remark',
              name: '备注',
              id: 8,
              prop: 'remark'
            },
            {
              fieldName: 'putinUserName',
              name: '创建人',
              id: 12,
              sort: true,
              prop: 'putinUserName'
            },
            {
              fieldName: 'createTime',
              name: '创建时间',
              id: 14,
              sort: true,
              prop: 'createTime'
            },
            {
              fieldName: 'checkStatus',
              name: '审核状态',
              id: 10,
              prop: 'checkStatus'
            },
            ]
          } else if (params.label == 99) {
            data = [{
              fieldName: 'settingName',
              name: '视频名称',
              id: 1,
              prop: 'settingName'
            }, {
              fieldName: 'settingValue',
              name: '配置值',
              id: 1,
              prop: 'settingValue'
            }, {
              fieldName: 'isEnable',
              name: '是否启用',
              id: 1,
            }, {
              fieldName: 'createUserName',
              name: '创建人',
              id: 1,
            }, {
              fieldName: 'createTime',
              name: '创建时间',
              id: 1,
            }, {
              fieldName: 'updateTime',
              name: '更新时间',
              id: 1,
            }, {
              fieldName: 'remark',
              name: '备注',
              id: 1,
              prop: 'remark'
            }, {
              fieldName: 'checkStatus',
              name: '状态',
              id: 1,
              // prop: 'checkStatus',
            },
            ]
          } else if (params.label == 101) {
            data = [
              {
                fieldName: 'id',
                name: '',
                id: 1,
                width: '1px',
                prop: 'id'
              }, {
                fieldName: 'deptName',
                name: '合伙人名称',
                id: 1,
                width: '200px',
                prop: 'deptName'
              }, {
                fieldName: 'rechargeSource',
                name: '充值渠道',
                id: 1,
                width: '200px',
                prop: 'rechargeSource'
              }, {
                fieldName: 'topUpPrice',
                name: '充值金额',
                id: 2,
                width: '120px',
                prop: 'topUpPrice'
              }, {
                fieldName: 'topUpDate',
                name: '充值时间',
                id: 3,
                width: '200px',
                prop: 'topUpDate'
              }, {
                fieldName: 'topUpFileName',
                name: '充值截图',
                id: 4,
                width: '200px',
                prop: 'topUpFileName'
              }, {
                fieldName: 'createUserName',
                name: '创建人',
                id: 5,
                width: '100px',
                prop: 'createUserName'
              }, {
                fieldName: 'createTime',
                name: '创建时间',
                id: 6,
                width: '200px',
                prop: 'createTime'
              },
            ]
          } else if (params.label == 102) {
            data = [
              {
                fieldName: 'id',
                name: '',
                id: 1,
                width: '1px',
                prop: 'id'
              },
              {
                fieldName: 'deptName',
                name: '合伙人名称',
                id: 2,
                width: '500px',
                prop: 'deptName'
              }, {
                fieldName: 'rechargeSource',
                name: '渠道',
                id: 2,
                width: '500px',
                prop: 'rechargeSource'
              }, {
                fieldName: 'balance',
                name: '余额',
                id: 3,
                width: '400px',
                prop: 'balance'
              }
            ]
          } else if (params.label == 103) {
            data = [{
              fieldName: 'putinPlatform',
              name: '投放平台',
              id: 1,
              sort: true,
              width: "200px",
              prop: 'putinPlatform'
            },
            {
              fieldName: 'category',
              name: '大类',
              id: 29,
              sort: true,
              prop: 'category'
            },
            {
              fieldName: 'putinMoney',
              name: '渠道充值金额',
              id: 2,
              sort: true,
              prop: 'putinMoney'
            },
            {
              fieldName: 'practicalPutinMoney',
              name: '渠道消耗金额',
              id: 3,
              sort: true,
              prop: 'practicalPutinMoney'
            },
            {
              fieldName: 'actualConsumptionMoney',
              name: '实际消耗金额',
              id: 6,
              sort: true,
              prop: 'actualConsumptionMoney'
            },
            {
              fieldName: 'putinDateStart',
              name: '投放开始日期',
              id: 7,
              sort: true,
              prop: 'putinDateStart'
            },
            {
              fieldName: 'putinDateEnd',
              name: '投放结束日期',
              id: 11,
              sort: true,
              prop: 'putinDateEnd'
            },
            {
              fieldName: 'contractDealCount',
              name: '合同成交数量',
              id: 8,
              sort: true,
              prop: 'contractDealCount'
            },
            {
              fieldName: 'contractAllMoney',
              name: '合同成交金额',
              id: 12,
              sort: true,
              prop: 'contractAllMoney'
            },
            {
              fieldName: 'receivablesDealMoneyNoTime',
              name: '回款成交金额',
              id: 29,
              sort: true,
              prop: 'receivablesDealMoney'
            },
            {
              fieldName: 'receivablesDealMoney',
              name: '实际回款成交金额',
              id: 9,
              sort: true,
              prop: 'receivablesDealMoney'
            },
            {
              fieldName: 'sjdqdRoi',
              name: '实际回款/渠道消耗ROI',
              id: 13,
              sort: true,
              prop: 'sjdqdRoi'
            },
            {
              fieldName: 'sjdsjRoi',
              name: '实际回款/实际消耗ROI',
              id: 14,
              sort: true,
              prop: 'sjdsjRoi'
            },
            {
              fieldName: 'allqdRoi',
              name: '回款/渠道消耗ROI',
              id: 15,
              sort: true,
              prop: 'allqdRoi'
            },
            {
              fieldName: 'allsjRoi',
              name: '回款/实际消耗ROI',
              id: 16,
              sort: true,
              prop: 'allsjRoi'
            },
            {
              fieldName: 'bdsjRoi',
              name: '实际合同/渠道消耗金额ROI',
              id: 17,
              sort: true,
              prop: 'bdsjRoi'
            },
            {
              fieldName: 'bdzmRoi',
              name: '实际合同/实际消耗金额ROI',
              id: 18,
              sort: true,
              prop: 'bdzmRoi'
            },
            {
              fieldName: 'cjkhRoi',
              name: '合同/渠道消耗金额ROI',
              id: 19,
              sort: true,
              prop: 'cjkhRoi'
            },
            {
              fieldName: 'cjhtRoi',
              name: '合同/实际消耗金额ROI',
              id: 20,
              sort: true,
              prop: 'cjhtRoi'
            },
            {
              fieldName: 'sjdqdRoi2',
              name: '年实际回款/渠道消耗ROI',
              id: 21,
              sort: true,
              prop: 'sjdqdRoi2'
            },
            {
              fieldName: 'sjdsjRoi2',
              name: '年实际回款/实际消耗ROI',
              id: 22,
              sort: true,
              prop: 'sjdsjRoi2'
            },
            {
              fieldName: 'allqdRoi2',
              name: '年回款/渠道消耗ROI',
              id: 23,
              sort: true,
              prop: 'allqdRoi2'
            },
            {
              fieldName: 'allsjRoi2',
              name: '年回款/实际消耗ROI',
              id: 24,
              sort: true,
              prop: 'allsjRoi2'
            },
            {
              fieldName: 'bdsjRoi2',
              name: '年实际合同/渠道消耗金额ROI',
              id: 25,
              sort: true,
              prop: 'bdsjRoi2'
            },
            {
              fieldName: 'bdzmRoi2',
              name: '年实际合同/实际消耗金额ROI',
              id: 26,
              sort: true,
              prop: 'bdzmRoi2'
            },
            {
              fieldName: 'cjkhRoi2',
              name: '年合同/渠道消耗金额ROI',
              id: 27,
              sort: true,
              prop: 'cjkhRoi2'
            },
            {
              fieldName: 'cjhtRoi2',
              name: '年合同/实际消耗金额ROI',
              id: 28,
              sort: true,
              prop: 'cjhtRoi2'
            },
            ]
          } else if (params.label == 104) {
            data = [
              {
                fieldName: 'id',
                name: '',
                id: 1,
                width: '1px',
                prop: 'id'
              }, {
                fieldName: 'deptName',
                name: '部门名称',
                id: 1,
                width: '200px',
                prop: 'deptName'
              }, {
                fieldName: 'topUpSource',
                name: '充值渠道',
                id: 2,
                width: '200px',
                prop: 'topUpSource'
              }, {
                fieldName: 'topUpPrice',
                name: '充值金额',
                id: 3,
                width: '150px',
                prop: 'topUpPrice'
              }, {
                fieldName: 'topUpDate',
                name: '充值时间',
                id: 4,
                width: '200px',
                prop: 'topUpDate'
              }, {
                fieldName: 'topUpFileName',
                name: '充值截图',
                id: 5,
                width: '200px',
                prop: 'topUpFileName'
              }, {
                fieldName: 'createUserName',
                name: '创建人',
                id: 6,
                width: '200px',
                prop: 'createUserName'
              }, {
                fieldName: 'createTime',
                name: '创建时间',
                id: 7,
                width: '200px',
                prop: 'createTime'
              },
            ]
          } else if (params.label == 105) {
            data = [
              {
                fieldName: 'id',
                name: '',
                id: 1,
                width: '1px',
                prop: 'id'
              },
              {
                fieldName: 'deptName',
                name: '部门名称',
                id: 2,
                width: '600px',
                prop: 'deptName'
              }, {
                fieldName: 'topUpSource',
                name: '充值渠道',
                id: 3,
                width: '450px',
                prop: 'topUpSource'
              },
              {
                fieldName: 'balance',
                name: '余额',
                id: 4,
                width: '580px',
                prop: 'balance'
              }
            ]
          } else if (params.label == 106) {
            data = [
              {
                fieldName: 'id',
                name: '',
                id: 1,
                width: '1px',
                prop: 'id'
              },
              {
                fieldName: 'categoryName',
                name: '大类名称',
                id: 2,
                width: '530px',
                prop: 'categoryName'
              },
              {
                fieldName: 'source',
                name: '学员来源',
                id: 3,
                width: '420px',
                prop: 'source'
              },
              {
                fieldName: 'sourceGroup',
                name: '分组',
                id: 4,
                width: '510px',
                prop: 'sourceGroup'
              }
            ]
          } else if (params.label != 'seas') {
            data = [{
              fieldName: 'putinPlatform',
              name: '投放平台',
              id: 1,
              sort: true,
              width: "200px",
              prop: 'putinPlatform'
            },
            {
              fieldName: 'category',
              name: '大类',
              id: 29,
              sort: true,
              prop: 'category'
            },
            {
              fieldName: 'putinMoney',
              name: '渠道充值金额',
              id: 2,
              sort: true,
              prop: 'putinMoney'
            },
            {
              fieldName: 'practicalPutinMoney',
              name: '渠道消耗金额',
              id: 3,
              sort: true,
              prop: 'practicalPutinMoney'
            },
            {
              fieldName: 'putinRebatesMoney',
              name: '渠道返点金额',
              id: 4,
              sort: true,
              prop: 'putinRebatesMoney'
            },
            {
              fieldName: 'putinCompensateMoney',
              name: '渠道赔付金额',
              id: 5,
              sort: true,
              prop: 'putinCompensateMoney'
            },
            {
              fieldName: 'actualConsumptionMoney',
              name: '实际消耗金额',
              id: 6,
              sort: true,
              prop: 'actualConsumptionMoney'
            },
            {
              fieldName: 'putinDateStart',
              name: '投放开始日期',
              id: 7,
              sort: true,
              prop: 'putinDateStart'
            },
            {
              fieldName: 'putinDateEnd',
              name: '投放结束日期',
              id: 11,
              sort: true,
              prop: 'putinDateEnd'
            },
            {
              fieldName: 'contractDealCount',
              name: '合同成交数量',
              id: 8,
              sort: true,
              prop: 'contractDealCount'
            },
            {
              fieldName: 'contractAllMoney',
              name: '合同成交金额',
              id: 12,
              sort: true,
              prop: 'contractAllMoney'
            },
            {
              fieldName: 'receivablesDealMoneyNoTime',
              name: '回款成交金额',
              id: 29,
              sort: true,
              prop: 'receivablesDealMoney'
            },
            {
              fieldName: 'receivablesDealMoney',
              name: '实际回款成交金额',
              id: 9,
              sort: true,
              prop: 'receivablesDealMoney'
            },
            {
              fieldName: 'sjdqdRoi',
              name: '实际回款/渠道消耗ROI',
              id: 13,
              sort: true,
              prop: 'sjdqdRoi'
            },
            {
              fieldName: 'sjdsjRoi',
              name: '实际回款/实际消耗ROI',
              id: 14,
              sort: true,
              prop: 'sjdsjRoi'
            },
            {
              fieldName: 'allqdRoi',
              name: '回款/渠道消耗ROI',
              id: 15,
              sort: true,
              prop: 'allqdRoi'
            },
            {
              fieldName: 'allsjRoi',
              name: '回款/实际消耗ROI',
              id: 16,
              sort: true,
              prop: 'allsjRoi'
            },
            {
              fieldName: 'bdsjRoi',
              name: '实际合同/渠道消耗金额ROI',
              id: 17,
              sort: true,
              prop: 'bdsjRoi'
            },
            {
              fieldName: 'bdzmRoi',
              name: '实际合同/实际消耗金额ROI',
              id: 18,
              sort: true,
              prop: 'bdzmRoi'
            },
            {
              fieldName: 'cjkhRoi',
              name: '合同/渠道消耗金额ROI',
              id: 19,
              sort: true,
              prop: 'cjkhRoi'
            },
            {
              fieldName: 'cjhtRoi',
              name: '合同/实际消耗金额ROI',
              id: 20,
              sort: true,
              prop: 'cjhtRoi'
            },
            {
              fieldName: 'sjdqdRoi2',
              name: '年实际回款/渠道消耗ROI',
              id: 21,
              sort: true,
              prop: 'sjdqdRoi2'
            },
            {
              fieldName: 'sjdsjRoi2',
              name: '年实际回款/实际消耗ROI',
              id: 22,
              sort: true,
              prop: 'sjdsjRoi2'
            },
            {
              fieldName: 'allqdRoi2',
              name: '年回款/渠道消耗ROI',
              id: 23,
              sort: true,
              prop: 'allqdRoi2'
            },
            {
              fieldName: 'allsjRoi2',
              name: '年回款/实际消耗ROI',
              id: 24,
              sort: true,
              prop: 'allsjRoi2'
            },
            {
              fieldName: 'bdsjRoi2',
              name: '年实际合同/渠道消耗金额ROI',
              id: 25,
              sort: true,
              prop: 'bdsjRoi2'
            },
            {
              fieldName: 'bdzmRoi2',
              name: '年实际合同/实际消耗金额ROI',
              id: 26,
              sort: true,
              prop: 'bdzmRoi2'
            },
            {
              fieldName: 'cjkhRoi2',
              name: '年合同/渠道消耗金额ROI',
              id: 27,
              sort: true,
              prop: 'cjkhRoi2'
            },
            {
              fieldName: 'cjhtRoi2',
              name: '年合同/实际消耗金额ROI',
              id: 28,
              sort: true,
              prop: 'cjhtRoi2'
            },
            ]
          }
          const fieldList = []
          const moneyFields = []
          for (let index = 0; index < data.length; index++) {
            const element = data[index]
            var width = 0
            if (!element.width) {
              if (element.name && element.name.length <= 6) {
                width = element.name.length * 15 + 45
              } else {
                width = 140
              }
            } else {
              width = element.width
            }

            // 金额字段 需要格式化
            if (element.formType === 'floatnumber') {
              moneyFields.push(element.fieldName || '')
            }

            fieldList.push({
              prop: element.fieldName,
              label: element.name,
              width: width,
              sortId: element.id
            })
          }

          this.moneyFields = moneyFields
          this.fieldList = fieldList
          // 获取好字段开始请求数据
          this.getList()
        }

      } else {
        // 获取好字段开始请求数据
        this.getList()
      }
    },
    /** 格式化字段 */
    fieldFormatter(row, column, cellValue) {
      if (this.moneyFields.includes(column.property)) {
        return separator(row[column.property] || 0)
      }
      // console.log(row, column, cellValue,column.property)
      // 如果需要格式化
      if (column.property === 'categories') {//大类
        if (!cellValue) cellValue = row.categories;
        return ['电商美工', '手绘插画', '影视后期'][cellValue - 1] || '--'
      }
      if (column.property === 'salesType') {
        if (!cellValue) cellValue = row.salesType;
        return ['电销', '网销'][cellValue - 1] || '--'
      }
      if (column.property === 'isTransform') {
        if (!cellValue) cellValue = row.isTransform;
        return ['否', '是'][cellValue] || '--'
      }
      if (column.property === 'topUpDate') {
        if (!cellValue) cellValue = row.topUpDate;
        return cellValue.substr(0, 10) || '--'
      }
      if (column.property === 'refundMaterial') {//退款资料
        if (Array.isArray(row.refundMaterial)) {
          return row.refundMaterial.length > 0 ? row.refundMaterial.join(',') : ''
        }
      }
      if (column.property === 'enclosure') {//回款审批资料
        if (Array.isArray(row.enclosure)) {
          return row.enclosure.length > 0 ? row.enclosure.join(',') : ''
        }
      }
      return row[column.property] === '' || row[column.property] === null ? '--' : row[column.property]
    },
    /** */
    /** */
    /** 搜索操作 */
    crmSearch(value) {
      this.currentPage = 1
      this.search = value
      if (this.fieldList.length) {
        this.getList()
      }
    },
    /** 列表操作 */
    // 当某一行被点击时会触发该事件
    handleRowClick(row, column, event) {
      if (column.type === 'selection') {
        return // 多选布局不能点击
      }

      if (this.crmType === 'leads') {
        if (column.property === 'leadsName' || column.property === 'customerName') {
          this.rowID = row.leadsId
          this.rowType = 'leads'
          this.showDview = true
        } else {
          this.showDview = false
        }
      } else if (this.crmType === 'roiMoney') {
        if (column.property === 'putinPlatform') {
          this.rowID = row.putinMoneyId
          this.rowType = 'roiMoney'
          this.showDview = true
          console.log(this.showDview, '是否显示')
        } else {
          this.showDview = false
        }
      } else if (this.crmType === 'crmPutinAllianceBusiness') {
        if (column.property === 'putinPlatform') {
          this.rowID = row.putinMoneyId
          this.rowType = 'crmPutinAllianceBusiness'
          this.showDview = true
          console.log(this.showDview, '是否显示')
        } else {
          this.showDview = false
        }
      } else if (this.crmType === 'putinStatistics') {
        if (column.property === 'putinStatisticsName') {
          this.rowID = row.roiId
          this.rowType = 'putinStatistics'
          this.showDview = true
        } else {
          this.showDview = false
        }
      } else if (this.crmType === 'allianceBusiness') {
        if (column.property === 'deptName') {
          this.rowID = row.id
          this.rowType = 'allianceBusiness'
          this.showDview = true
        } else {
          this.showDview = false
        }
      } else if (this.crmType === 'customer') {
        if (column.property === 'businessCheck' && row.businessCount > 0) {
          return // 列表查看商机不展示详情
        }
        if (column.property === 'customerName') {
          this.rowID = row.customerId
          this.rowType = 'customer'
          this.showDview = true
        } else {
          this.showDview = false
        }
      }
      else if (this.crmType === 'vipStudents') {
        if (column.property === 'customerName') {
          this.rowID = row.studentId
          this.rowType = 'vipStudents'
          this.showDview = true
        } else {
          this.showDview = false
        }
      }
      else if (this.crmType === 'contacts') {
        if (column.property === 'customerName') {
          this.rowID = row.customerId
          this.rowType = 'customer'
          this.showDview = true
        } else if (column.property === 'name') {
          this.rowID = row.contactsId
          this.rowType = 'contacts'
          this.showDview = true
        } else {
          this.showDview = false
        }
      } else if (this.crmType === 'business') {
        if (column.property === 'customerName') {
          this.rowID = row.customerId
          this.rowType = 'customer'
          this.showDview = true
        } else if (column.property === 'businessName') {
          this.rowID = row.businessId
          this.rowType = 'business'
          this.showDview = true
        } else {
          this.showDview = false
        }
      } else if (this.crmType === 'contract') {
        if (column.property === 'customerName') {
          this.rowID = row.customerId
          this.rowType = 'customer'
          this.showDview = false
        } else if (column.property === 'businessName') {
          this.rowID = row.businessId
          this.rowType = 'business'
          this.showDview = true
        } else if (column.property === 'contactsName') {
          this.rowID = row.contactsId
          this.rowType = 'contacts'
          this.showDview = true
        } else if (column.property === 'num') {
          this.rowID = row.contractId
          this.rowType = 'contract'
          this.showDview = true
        } else {
          this.showDview = false
        }
      } else if (this.crmType === 'product') {
        if (column.property === 'name') {
          this.rowID = row.productId
          this.showDview = true
        } else {
          this.showDview = false
        }
      } else if (this.crmType === 'receivables') {
        if (column.property === 'customerName') {
          this.rowID = row.customerId
          this.rowType = 'customer'
          this.showDview = false
        } else if (column.property === 'number') {
          this.rowID = row.receivablesId
          this.rowType = 'receivables'
          this.showDview = true
        } else {
          this.showDview = false
        }
      } else if (this.crmType === 'refund') {
        if (column.property === 'number') {
          this.rowID = row.refundId
          this.rowType = 'refund'
          this.showDview = true
        } else {
          this.showDview = false
        }
      } else if (this.crmType == 'visit') {
        if (column.property === 'visitNumber') {
          this.rowID = row.visitId
          this.rowType = 'visit'
          this.showDview = true
        } else if (column.property === 'customerName') {
          this.rowID = row.customerId
          this.rowType = 'customer'
          this.showDview = true
        } else if (column.property === 'contractNum') {
          this.rowID = row.contractId
          this.rowType = 'contract'
          this.showDview = true
        } else if (column.property === 'contactsName') {
          this.rowID = row.contactsId
          this.rowType = 'contacts'
          this.showDview = true
        } else {
          this.showDview = false
        }
      } else if (this.crmType === 'headquartersBusiness') {
        if (column.property === 'deptName') {
          this.rowID = row.id
          this.rowType = 'headquartersBusiness'
          this.showDview = true
        } else {
          this.showDview = false
        }
      } else if (this.crmType === 'overdue') {
        if (column.property === 'number') {
          this.rowID = row.overdueId
          this.rowType = 'overdue'
          this.showDview = true
        } else {
          this.showDview = false
        }
      }
      if (this.showDview) {
        this.$store.commit('SET_detailThis', {
          thia: this
        })
        this.$store.commit('SET_COLLAPSE', this.showDview)
      }
    },
    /**
     * 导出 线索 学员 联系人 产品
     * @param {*} data
     */
    // 导出操作
    exportInfos() {
      var params = {
        search: this.search,
        type: this.isSeas ? crmTypeModel.pool : crmTypeModel[this.crmType] // 9是公海
      }
      if (this.sceneId) {
        params.sceneId = this.sceneId
      }

      // 公海切换
      if (this.poolId) {
        params.poolId = this.poolId
      }

      if (this.filterObj && this.filterObj.length > 0) {
        params.searchList = this.filterObj
      }
      if (this.crmType == 'roiMoney' || this.crmType == 'putinStatistics') {
        params.coursePeriods = this.kcinput_s;
        console.log(12345678)
        console.log(this.datevalue_s, 'crmType,datevalue_s');
        if (this.datevalue_s) {
          params.startDate = this.datevalue_s[0];
          params.endDate = this.datevalue_s[1];
        }
        params.putinPlatform = this.tfvalue_s.toString();
      }
      if (this.crmType == 'refund') {
        if (this.refundCategory) {
          params.refundCategory = this.refundCategory;
        }
      }
      if (this.crmType == 'contract') {
        if (this.activeName == 'second') {
          params.contractCategory = '账单合同'
        } else if (this.activeName == 'third') {
          params.contractCategory = '首付款合同'
        } else if (this.activeName == 'fourth') {
          params.contractCategory = '全款/复购合同'
        } else if (this.activeName == 'fifth') {
          params.contractCategory = '线下合同'
        }
      }
      let request
      // 公海的请求
      if (this.isSeas) {
        request = crmCustomerPoolExcelAllExport
      } else {
        request = {
          customer: crmCustomerExcelAllExportAPI,
          leads: crmLeadsExcelAllExportAPI,
          contacts: crmContactsExcelAllExportAPI,
          business: crmBusinessExcelAllExportAPI,
          contract: crmContractExcelAllExportAPI,
          receivables: crmReceivablesExcelAllExportAPI,
          refund: crmRefundExcelAllExportAPI,
          product: crmProductExcelAllExportAPI,
          roiMoney: crmRoiExcelAllExportAPI,
          putinStatistics: crmputinStatisticsExcelAllExportAPI,
          vipStudents: crmCustomerVipExcelAllExportAPI,
          overdue: crmOverdueExcelAllExportAPI,
        }[this.crmType]
      }
      const loading = Loading.service({
        fullscreen: true,
        text: '导出中...'
      })
      request(params)
        .then(res => {
          downloadExcelWithResData(res)
          loading.close()
          setTimeout(() => {
            this.$bus.emit("document-visibility", 'visible');
          }, 2500);
        })
        .catch(() => {
          loading.close()
          setTimeout(() => {
            this.$bus.emit("document-visibility", 'visible');
          }, 2500);
        })
    },
    /** 筛选操作 */
    handleFilter(data) {
      // console.log('handle-data', data)
      this.filterObj = data
      this.currentPage = 1
      this.getList()
    },
    /** 场景操作 */
    handleScene(data) {
      this.sceneId = data.id
      this.sceneName = data.name
      this.currentPage = 1
      this.getFieldList()
    },
    /** 勾选操作 */
    handleHandle(data) {
      console.log(data);
      if (data && data.type) {
        if (['alloc', 'get', 'transfer', 'transform', 'delete', 'put_seas', 'exit-team', 'transcancel'].includes(data.type)) {
          this.showDview = false
        }
      }
      if (data && data.type && data.type == 'clear-sort') {
        this.getMainTable().clearSort()
        this.sortChange()
      } else {
        this.getMainTable().clearSelection()
        this.getList()
      }
    },
    /**
     * 获取table
     */
    getMainTable() {
      let table = null
      // console.log('this.$childrenthis.$children-----------------------')
      console.log(this.$children)
      this.$children.forEach(item => {
        if (item.$options && item.$options.name === 'ElTable') {
          table = item
        }
      })
      // console.log(table)
      // console.log(table.clearSelection())

      return table
    },

    /** 自定义字段管理 */
    setSave() {
      this.getFieldList(true)
    },
    /** */
    /** 页面头部操作 */
    listHeadHandle(data) {
      console.log('走了这里-------------------123')
      if (data.type === 'save-success' || data.type === 'import-crm') {
        console.log('走了这里-------------------456')
        // 重新请求第一页数据
        this.currentPage = 1
        this.getList()
      }
    },

    // 回款还款计划单加
    repayClick(data) {
      this.currentPage = 1
      this.defaultGenerate = data.defaultGenerate
      this.getList()
    },
    /**
     * 字段排序
     */
    sortChange(column, prop, order) {
      this.currentPage = 1
      this.sortData = column || {}
      this.getList()
    },
    /** 勾选操作 */
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      this.selectionList = val // 勾选的行
      // this.$refs.crmTableHead.headSelectionChange(val)
      this.$refs.crmTableManage.headSelectionChange(val)
      if (this.selectionList.length > 0) {
        this.removeHeight = 41
      } else {
        this.removeHeight = 0
      }

    },
    // 当拖动表头改变了列的宽度的时候会触发该事件
    handleHeaderDragend(newWidth, oldWidth, column, event) {
      if (column.property) {
        let request = null
        var sortId
        this.fieldList.forEach(e => {
          if (column.property === e.prop) {
            sortId = e.sortId
          }
        })
        if (!sortId) {
          return
        }
        const params = {
          id: sortId,
          width: newWidth,
          field: column.property
        }
        if (this.isSeas) {
          if (!this.poolId) {
            return
          }
          request = crmPoolFieldColumnWidthAPI
          params.poolId = this.poolId
        } else {
          request = crmFieldColumnWidthAPI
        }

        request(params)
          .then(res => { })
          .catch(() => { })
      }
    },
    // 更改每页展示数量
    handleSizeChange(val) {
      Lockr.set('crmPageSizes', val)
      this.pageSize = val
      this.getList()
    },
    // 更改当前页数
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },
    // 0待审核、1审核中、2审核通过、3已拒绝 4已撤回 5未提交
    getStatusStyle(status) {
      return {
        backgroundColor: this.getStatusColor(status)
      }
    },

    /**
     * 切换关注状态
     * @param index
     * @param status
     */
    toggleStar(data) {
      this.loading = true

      const request = {
        leads: crmLeadsStarAPI,
        customer: crmCustomerStarAPI,
        contacts: crmContactsStarAPI,
        business: crmBusinessStarAPI,
        vipStudents: crmCustomerVipStarAPI
      }[this.crmType]

      const params = {}
      params[`id`] = data[`${this.crmType == 'vipStudents' ? 'student' : this.crmType}Id`]

      request(params).then(() => {
        this.loading = false
        this.$message.success(data.star > 0 ? '取消关注成功' : '关注成功')
        data.star = data.star > 0 ? 0 : 1
      }).catch(() => {
        this.loading = false
      })
    },
  },

  beforeDestroy() {
    this.$bus.off('updateList')
  }
}
